import { ref } from 'vue'

type EventCallback = (...args: any[]) => void

class EventBus {
  private events: Map<string, EventCallback[]> = new Map()

  // 订阅事件
  on(event: string, callback: EventCallback) {
    if (!this.events.has(event)) {
      this.events.set(event, [])
    }
    this.events.get(event)!.push(callback)
  }

  // 取消订阅
  off(event: string, callback: EventCallback) {
    const callbacks = this.events.get(event)
    if (callbacks) {
      const index = callbacks.indexOf(callback)
      if (index > -1) {
        callbacks.splice(index, 1)
      }
    }
  }

  // 发出事件
  emit(event: string, ...args: any[]) {
    const callbacks = this.events.get(event)
    if (callbacks) {
      callbacks.forEach(callback => callback(...args))
    }
  }

  // 一次性订阅
  once(event: string, callback: EventCallback) {
    const onceCallback = (...args: any[]) => {
      callback(...args)
      this.off(event, onceCallback)
    }
    this.on(event, onceCallback)
  }
}

export const eventBus = new EventBus()

// 定义事件类型
export const Events = {
  // 数据刷新事件
  REFRESH_INVESTMENT_DATA: 'refresh_investment_data',
  REFRESH_STAKING_DATA: 'refresh_staking_data',
  REFRESH_WALLET_DATA: 'refresh_wallet_data',

  // 质押成功事件
  STAKING_SUCCESS: 'staking_success',

  // 提现成功事件
  WITHDRAW_SUCCESS: 'withdraw_success',

  // Upbit 购买成功事件
  UPBIT_PURCHASE_SUCCESS: 'upbit_purchase_success'
} as const

export type EventType = typeof Events[keyof typeof Events]
